package com.demon.framework.boot.filter;

import com.demon.framework.common.model.constants.HeaderConstants;
import com.demon.framework.common.model.constants.LogConstants;
import com.demon.framework.util.gen.SnowflakeIdWorker;
import com.demon.framework.util.request.RequestContextUtil;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author Demon-HY
 * @description
 * @date 2020/6/1 17:55
 */
@Component
@WebFilter(filterName = "logbackFilter")
public class LogbackFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void destroy() {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        String requestId = RequestContextUtil.genRequestId();
        MDC.put(LogConstants.UNIQUE_ID, requestId);
        // 写入response header
        HttpServletResponse resp = (HttpServletResponse) servletResponse;
        resp.setHeader(HeaderConstants.REQUEST_ID, requestId);

        try {
            filterChain.doFilter(servletRequest, servletResponse);
        } finally {
            MDC.remove(LogConstants.UNIQUE_ID);
        }
    }
}
